package com.swufe.team;

import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MyListActivity extends ListActivity implements Runnable {


    private static final String TAG ="List" ;
    Handler handle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List<Element> list1=new ArrayList<>();
        String[] list_data={"one","two","three","four"};
        ListAdapter adapter=new ArrayAdapter<Element>(this, android.R.layout.simple_list_item_activated_1,list1);
        setListAdapter(adapter);


        handle=new Handler(){
            public void handleMessage(Message msg){
                if (msg.what==5){
                    List<String> list2= (List<String>) msg.obj;
               ListAdapter adapter = new ArrayAdapter<String>(MyListActivity.this, android.R.layout.simple_list_item_activated_1,list2);
               setListAdapter(adapter);
           }
           super.handleMessage(msg);
        }
    };

    Thread t=new Thread(this);
    t.start();

    }

    @Override
    public void run() {
        Log.i(TAG, "run: Running....");
        try {
            Thread.sleep(3000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }

        List<String> reList=new ArrayList<String>();

        try {
            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
            String title=doc.title();
//            Element table= doc.getElementsByTag("table").first();
            Elements trs=doc.getElementsByTag("tr");
            for (Element tr:trs ) {
                Elements tds=tr.getElementsByTag("td");
                if(tds.size()>0) {
                    String td1 = tds.first().text();
                    String td2 = tds.get(5).text();
                    reList.add(td1+"==>"+td2);


                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Message msg=handle.obtainMessage(5,reList);
        handle.sendMessage(msg);
        Log.i(TAG, "run: sendMessage ok");




    }
}